import uuid

from rest_framework import viewsets, mixins
from rest_framework.response import Response

from carts.models import CartModel
from orders.filters import OrderFilter
from orders.models import OrderModel, OrderGoodsModel
from orders.serialziers import OrderSerializer
from utils.authentication import UserAuthentication
from utils.errors import ParamsException


class OrderView(viewsets.GenericViewSet,
                mixins.CreateModelMixin,
                mixins.ListModelMixin):

    queryset = OrderModel.objects.all()

    serializer_class = OrderSerializer

    authentication_classes = (UserAuthentication,)

    filter_class = OrderFilter

    # def list(self, request, *args, **kwargs):
    #     """
    #     data: [{
    #       'order_goods_info':{
    #         'o_goods': {'商品信息'}
    #       },
    #       ’o_price‘: ’‘
    #     }]
    #     # """
        # queryset = self.filter_queryset(self.get_queryset())
        # serialzier = self.get_serializer(queryset, many=True)
        # return Response(serialzier.data)



    def create(self, request, *args, **kwargs):
        # 重构创建订单和订单详情表内容
        user = request.user
        # 从购物车中取出需要下单的商品信息
        carts_goods = CartModel.objects.filter(user=user,
                                               is_select=True).all()
        if not carts_goods:
            raise ParamsException({'code': 1009, 'msg': '请添加商品再下单'})
        # 创建订单
        order = OrderModel.objects.create(user=user,
                                          o_num=uuid.uuid4().hex)
        # 创建订单详情表
        for cart in carts_goods:
            OrderGoodsModel.objects.create(order=order,
                                           goods=cart.goods,
                                           goods_num=cart.c_num)
            # 购物车中已下单的商品需删除
            cart.delete()
        res = {
            'msg': '下单成功'
        }
        return Response(res)